<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :visible="visible"
    :width="$store.getters.isMobile ? 350 : 450"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-form-item label="选择公司" v-bind="validateInfos.org_branch_id">
        <a-select
          v-model:value="formData.org_branch_id"
          placeholder="请选择公司"
          :options="companyList"
          :disabled="disabledCompany"
          allowClear
        />
      </a-form-item>
      <a-form-item label="签约方式" v-bind="validateInfos.type">
        <a-radio-group name="radioGroup" v-model:value="formData.type">
          <a-radio value="0">E签宝签约</a-radio>
          <a-radio value="1">普通签约</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="应用id"
        v-bind="validateInfos.app_id"
        v-if="formData.type == 0"
      >
        <a-input placeholder="请输入" v-model:value="formData.app_id" />
      </a-form-item>
      <a-form-item
        label="应用秘钥"
        v-bind="validateInfos.app_scert"
        v-if="formData.type == 0"
      >
        <a-input placeholder="请输入" v-model:value="formData.app_scert" />
      </a-form-item>
      <a-form-item
        label="rsa秘钥"
        v-bind="validateInfos.rsa_key"
        v-if="formData.type == 0"
      >
        <a-input placeholder="请输入" v-model:value="formData.rsa_key" />
      </a-form-item>
      <!-- 默认选中单页盖章，可多选 -->
      <a-form-item
        label="盖章方式"
        v-bind="validateInfos.sign_type"
        v-if="formData.type == 0"
      >
        <a-checkbox-group
          v-model:value="formData.sign_type"
          style="width: 100%"
        >
          <a-row>
            <a-col :span="8">
              <a-checkbox value="1">单页盖章</a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox value="2">骑缝章</a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item
        label="电子印章"
        v-bind="validateInfos.electronic_seal"
        v-if="formData.type == 1"
      >
        <a-upload
          :action="$utils.imgAction"
          :headers="{ 'org-token': $store.getters.token }"
          :multiple="false"
          v-model:file-list="fileList"
          @change="handleUploadChange"
          name="image"
          :data="{
            dir: 'contract',
          }"
          accept="image/png"
          list-type="picture-card"
        >
          <div v-if="fileList.length < 1">
            <template v-if="true">
              <plus-outlined style="font-size: 18px" />
            </template>
          </div>
        </a-upload>
        <div style="font-size: 12px; color: #999999">限制1张，格式为png</div>
      </a-form-item>
      <a-form-item label="发送方式" v-bind="validateInfos.sending">
        <a-checkbox-group v-model:value="formData.sending" style="width: 100%">
          <a-row>
            <a-col :span="8">
              <a-checkbox value="1"
                >短信发送

                <!-- <a-tooltip>
                  <template #title>文案</template>
                  <QuestionCircleOutlined />
                </a-tooltip> -->
              </a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox value="2"
                >邮件发送
                <!-- <a-tooltip>
                  <template #title>文案</template>
                  <QuestionCircleOutlined />
                </a-tooltip> -->
              </a-checkbox>
            </a-col>
            <a-col :span="8">
              <a-checkbox value="3"
                >公众号发送
                <!-- <a-tooltip>
                  <template #title>文案</template>
                  <QuestionCircleOutlined />
                </a-tooltip> -->
              </a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="closeModal">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import { message, Form } from "ant-design-vue";
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import request from "../../../../common/utils/request";
import { PlusOutlined, QuestionCircleOutlined } from "@ant-design/icons-vue";
const useForm = Form.useForm;

export default defineComponent({
  name: "ElContractSettingAdd",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String, undefined],
      default: undefined,
    },
  },
  components: { PlusOutlined, QuestionCircleOutlined },
  setup(props, context) {
    const state = reactive({
      fileList: [],
      companyList: [],
      disabledCompany: false,
    });
    const formData = reactive({
      org_branch_id: undefined,
      app_id: "",
      app_scert: "",
      rsa_key: "",
      sign_type: ["1"],
      type: "0",
      sending: [],
      electronic_seal: "",
    });
    const ruleRef = reactive({
      app_id: [{ required: true, message: "必填" }],
      app_scert: [{ required: true, message: "必填" }],
      rsa_key: [{ required: true, message: "必填" }],
      sign_type: [{ required: true, message: "必填" }],
      sending: [{ required: true, message: "必填" }],
      org_branch_id: [{ required: true, message: "必填" }],
    });
    const { resetFields, validate, validateInfos } = useForm(formData, ruleRef);
    const title = computed(() => {
      return props.id || props.id == 0 ? "编辑电子合同章" : "新增电子合同章";
    });

    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              formData.electronic_seal = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        formData.electronic_seal = "";
      }
      state.fileList = resFileList;
    };

    watch(
      () => formData.type,
      (val) => {
        if (val == 1) {
          ruleRef.app_id[0].required = false;
          ruleRef.app_scert[0].required = false;
          ruleRef.rsa_key[0].required = false;
          ruleRef.electronic_seal = [{ required: true, message: "必填" }];
        } else {
          ruleRef.app_id[0].required = true;
          ruleRef.app_scert[0].required = true;
          ruleRef.rsa_key[0].required = true;
          ruleRef.electronic_seal = [{ required: false, message: "必填" }];
        }
      }
    );

    const closeModal = () => {
      context.emit("handleCancel");
    };

    const onSubmit = () => {
      validate().then(() => {
        let params = JSON.parse(JSON.stringify(formData));
        let sign_type = JSON.parse(JSON.stringify(formData.sign_type));

        if (params.sending.length > 0) {
          params.is_sms = 0;
          params.is_email = 0;
          params.is_weixin = 0;
          if (params.sending.includes("1")) {
            params.is_sms = 1;
          }
          if (params.sending.includes("2")) {
            params.is_email = 1;
          }
          if (params.sending.includes("3")) {
            params.is_weixin = 1;
          }
          params.sending = undefined;
        }
        params.needMsg = true;
        params.sign_type = sign_type.join();
        const success = (res) => {
          message.success(res.msg || "保存成功！");
          context.emit("handleSuccess");
        };
        if (props.id || props.id == 0) {
          // 编辑
          params.id = props.id;
          request
            .put("/org", "/esign/alter", params)
            .then((res) => success(res));
        } else {
          // 新增
          request
            .post("/org", "/esign/create", params)
            .then((res) => success(res));
        }
      });
    };

    const getDetail = () => {
      request.get("/org", "/esign/detail", {id: props.id}).then((res) => {
        const { detail } = res;
        if (detail && (detail.id || detail.id == 0)) {
          formData.app_id = detail?.app_id || '';
          formData.app_scert = detail?.app_scert || '';
          formData.rsa_key = detail?.rsa_key || '';
          if (detail.sign_type) {
            formData.sign_type = detail.sign_type.split(",");
          }
          if (detail.type || detail.type == 0) {
            formData.type = String(detail.type);
          }
          formData.sending = [];
          if (detail.is_email) {
            formData.sending.push("2");
          }
          if (detail.is_sms) {
            formData.sending.push("1");
          }
          if (detail.is_weixin) {
            formData.sending.push("3");
          }
          state.companyList = [
            {
              label: detail.branchName,
              value: detail.org_branch_id,
            }
          ]
          formData.org_branch_id = detail.org_branch_id;
          if (detail.electronic_seal) {
            state.fileList = [
              {
                uid: "1",
                url: detail.electronic_seal,
              },
            ];
            formData.electronic_seal = detail.electronic_seal;
          } else {
            state.fileList = [];
            formData.electronic_seal = "";
          }
        }
      });
    };

    const getCompanyList = () => {
      request.get("/org", "/esign/branchList").then((res) => {
        state.companyList = (res?.list || []).map((v) => {
          return {
            value: v.id,
            label: v.company,
          }
        })
      });
    };

    const init = () => {
      if (props.id || props.id == 0) {
        // 编辑
        state.disabledCompany = true;
        getDetail();
      } else {
        // 新增
        getCompanyList();
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          state.fileList = [];
          state.companyList = [];
          state.disabledCompany = false;
        }
      }
    );
    return {
      ...toRefs(state),
      formData,
      validateInfos,
      title,
      closeModal,
      onSubmit,
      handleUploadChange,
    };
  },
});
</script>
<style lang="less" scoped>
.flip-list-move {
  transition: transform 0.5s;
}
.no-move {
  transition: transform 0s;
}
.ghost {
  opacity: 0.5;
  background: @primary-color-bg;
}
.list-group {
  min-height: 20px;
}
.list-group-item {
  cursor: move;
  height: 50px;
  display: flex;
  align-items: center;
  border: 1px solid #f4f4f4;
  padding: 20px;
  font-size: 16px;
  .title {
    margin-left: 20px;
  }
}

:deep(.ant-upload.ant-upload-select-picture-card) {
  width: 55px !important;
  height: 55px !important;
  display: flex;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  border-radius: 5px;
  margin-bottom: 0;
}
:deep(.ant-upload.ant-upload-select-picture-card > .ant-upload) {
  padding: 5px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
:deep(.anticon-plus) {
  color: #d9d9d9 !important;
}
:deep(.ant-upload-list-picture-card-container) {
  width: 57px;
  height: 56px;
  margin-bottom: 0px;
}
:deep(.ant-upload-list-picture-card .ant-upload-list-item) {
  width: 57px;
  height: 56px;
  padding: 0 !important;
  border-radius: 5px;
}

:deep(.ant-upload-list-picture-card .ant-upload-list-item-info) {
  border-radius: 5px;
}
:deep(.ant-row) {
  flex-flow: initial;
}
:deep(.ant-form-item) {
  flex-direction: column !important;
}
</style>
